<?php
class ControllerSaleLgiLogcenterBill extends Controller {
  private $error = array();

  public function export(){
    $logcenter_bill_id = I('get.logcenter_bill_id');
    if(!$logcenter_bill_id){
      $logcenter_bill_id = 0;
    }
    $this->load->model('sale/logcenter_bill');
    $logcenter_bill = $this->model_sale_logcenter_bill->getLogcenterBill($logcenter_bill_id);
    $data['logcenter_bill'] = $logcenter_bill;
    if(!$logcenter_bill){
      $this->load->language('error/not_found');
 
      $this->document->setTitle($this->language->get('heading_title'));

      $data['heading_title'] = $this->language->get('heading_title');
 
      $data['text_not_found'] = $this->language->get('text_not_found');
 
      $data['breadcrumbs'] = array();

      $data['breadcrumbs'][] = array(
        'text' => $this->language->get('heading_title'),
        'href' => $this->url->link('error/not_found', 'token=' . $this->session->data['token'], 'SSL')
      );
 

      $data['footer'] = $this->load->controller('common/footer');
 
      $this->response->setOutput($this->load->view('error/not_found.tpl', $data));
    }
    $logcenter_bill_orders_info = $this->model_sale_logcenter_bill->getLogcenterBillOrdersInfo($logcenter_bill_id);
    $logcenter_bill_orders = $this->model_sale_logcenter_bill->getLogcenterBillOrders($logcenter_bill_id);
    $order_num = count($logcenter_bill_orders);
    $order_total = $logcenter_bill['order_total'];

    $this->load->library('PHPExcel/PHPExcel');
    $objReader = PHPExcel_IOFactory::createReader('Excel5');
    $objPHPExcel = $objReader->load(DIR_SYSTEM . "template/logcenter_bill_tpl.xls"); 
    $objPHPExcel->getProperties()->setCreator("Think-tec")
               ->setLastModifiedBy("Think-tec")
               ->setTitle("BHZ物流营销中心对账单")
               ->setSubject("BHZ物流营销中心对账单")
               ->setDescription("BHZ物流营销中心对账单")
               ->setKeywords("BHZ, Think-tec")
               ->setCategory("Think-tec");
    // $objPHPExcel->setActiveSheetIndex(0);
    $objActSheet = $objPHPExcel->getActiveSheet();
    $objActSheet->setCellValue('L3', $order_num);
    $objActSheet->setCellValue('N3', '￥'.$order_total);

    $row_num = 4;
    $styleBorderOutline = array(
      'borders' => array(
        'outline' => array(
          'style' => PHPExcel_Style_Border::BORDER_THIN,
        ),
      ),
    );
    $objPHPExcel->getActiveSheet()->insertNewRowBefore(5, count($logcenter_bill_orders_info));
    $count = 0;
    foreach ($logcenter_bill_orders_info as $key => $order_info) {
      $row_num++;
      $objActSheet->setCellValue('A'.$row_num, $row_num-4);
      $objActSheet->setCellValue('B'.$row_num, date('m-d', strtotime($order_info['date_added'])));
      $objActSheet->setCellValue('C'.$row_num, $order_info['order_id']);
      $objActSheet->setCellValue('D'.$row_num, $order_info['shipping_company']);
      $objActSheet->setCellValue('E'.$row_num, date('m-d', strtotime($order_info['date_modified'])));
      $objActSheet->setCellValue('F'.$row_num, '');
      $objActSheet->setCellValue('G'.$row_num, date('m-d', strtotime($order_info['date_modified'])));
      $objActSheet->setCellValue('H'.$row_num, '');
      $objActSheet->setCellValue('I'.$row_num, $order_info['vendor_id']);
      $objActSheet->setCellValue('J'.$row_num, $order_info['vendor_name']);
      $objActSheet->setCellValue('K'.$row_num, $order_info['product_name']);
      $objActSheet->setCellValue('L'.$row_num, $order_info['sku']);
      $objActSheet->setCellValue('M'.$row_num, $order_info['quantity']);
      // $objActSheet->setCellValue('M'.$row_num, $order_info['price']);
      // $objActSheet->setCellValue('N'.$row_num, $order_info['total']);
      // $objActSheet->setCellValue('O'.$row_num, $order_info['comment']);
      $objActSheet->setCellValue('N'.$row_num, $order_info['comment']);
      $objActSheet->mergeCells('N'.$row_num.':'.'N'.$row_num);
    }
    // $objPHPExcel->getActiveSheet()->getStyle('A5'.':'.'O'.$row_num)->applyFromArray($styleBorderOutline);
    
    $objActSheet->setTitle('物流营销中心对账单');


    $objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007');
    ob_end_clean();
    // Redirect output to a client’s web browser (Excel2007)
    header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
    header('Content-Disposition: attachment;filename="LOG_BILL_BHZ_'.date('Y-m-d-H-i',time()).'.xlsx"');
    header('Cache-Control: max-age=0');
    // If you're serving to IE 9, then the following may be needed
    header('Cache-Control: max-age=1');
    // If you're serving to IE over SSL, then the following may be needed
    header ('Expires: Mon, 26 Jul 1997 05:00:00 GMT'); // Date in the past
    header ('Last-Modified: '.gmdate('D, d M Y H:i:s').' GMT'); // always modified
    header ('Cache-Control: cache, must-revalidate'); // HTTP/1.1
    header ('Pragma: public'); // HTTP/1.0
    $objWriter->save('php://output'); 
    exit;
  }

  public function index() {

    $this->document->setTitle('物流营销中心对账单');

    $this->load->model('sale/logcenter_bill');

    $this->getList();
  }

  public function view(){

    $this->document->setTitle('查看物流营销中心对账单');

    $this->document->addScript('view/javascript/angular.js');
    $this->document->addScript('view/javascript/bhz_ctl.js');

    $this->load->model('sale/logcenter_bill');
    $data['breadcrumbs'] = array();

    $data['breadcrumbs'][] = array(
      'text' => $this->language->get('text_home'),
      'href' => $this->url->link('common/dashboard', 'token=' . $this->session->data['token'], 'SSL')
    );

    $data['breadcrumbs'][] = array(
      'text' => '物流营销中心对账单',
      'href' => $this->url->link('sale/logcenter_bill', 'token=' . $this->session->data['token'] , 'SSL')
    );

    $data['token'] = $this->session->data['token'];

    $id = I('get.logcenter_bill_id');
    if(!$id){
      $id=0;
    }
    

    if (isset($this->session->data['error'])) {
      $data['error_warning'] = $this->session->data['error'];

      unset($this->session->data['error']);
    } elseif (isset($this->error['warning'])) {
      $data['error_warning'] = $this->error['warning'];
    } else {
      $data['error_warning'] = '';
    }

    if (isset($this->session->data['success'])) {
      $data['success'] = $this->session->data['success'];

      unset($this->session->data['success']);
    } else {
      $data['success'] = '';
    }
    
    $logcenter_bill = $this->model_sale_logcenter_bill->getLogcenterBill($id);
    $data['logcenter_bill'] = $logcenter_bill;
    $logcenter_bill_orders = $this->model_sale_logcenter_bill->getLogcenterBillOrders($id);
    $data['logcenter_bill_orders'] = $logcenter_bill_orders;
    $logcenter_bill_histories = $this->model_sale_logcenter_bill->getLogcenterBillHistories($id);
    $data['logcenter_bill_histories'] = $logcenter_bill_histories;

    
    switch ($logcenter_bill['status']) {
      case '1':
        $data['change_status_text'] = '确认对账单';
        break;
      case '3':
        $data['change_status_text'] = '已收款';
        break;
      default:
        $data['change_status_text'] = '';
        break;
    }

    $data['header'] = $this->load->controller('common/header');
    $data['column_left'] = $this->load->controller('common/column_left');
    $data['footer'] = $this->load->controller('common/footer');

    $this->response->setOutput($this->load->view('sale/lgi_logcenter_bill_view.tpl', $data));
  }

  protected function getList() {
    $page = I('get.page');
    if(!$page){
      $page = 1;
    }
    $filter_logcenter_bill_id = I('get.filter_logcenter_bill_id');
    $filter_logcenter_name = I('get.filter_logcenter_name');
    $filter_year_month = I('get.filter_year_month');
    $filter_total = I('get.filter_total');
    $filter_date_added = I('get.filter_date_added');
    $filter_logcenter_bill_status = I('get.filter_logcenter_bill_status');
    
    if($filter_logcenter_bill_id) {$filter['logcenter_bill_id'] = $filter_logcenter_bill_id;}
    // if($filter_logcenter_name) {$filter['logcenter_name'] = array('like', '%'.$filter_logcenter_name.'%');}
    if($filter_year_month) {$filter['DATE_FORMAT(lb.year_month, "%Y-%m")'] = $filter_year_month;}
    if($filter_total) {$filter['total'] = $filter_total;}
    if($filter_date_added) {$filter['date_added'] = $filter_date_added;}
    if($filter_logcenter_bill_status || $filter_logcenter_bill_status==0) {
      $filter['lb.status'] = $filter_logcenter_bill_status;
    }

    $data['filter_logcenter_bill_id'] = $filter_logcenter_bill_id;
    $data['filter_logcenter_name'] = $filter_logcenter_name;
    $data['filter_year_month'] = $filter_year_month;
    $data['filter_total'] = $filter_total;
    $data['filter_date_added'] = $filter_date_added;
    $data['filter_logcenter_bill_status'] = $filter_logcenter_bill_status;

    if($filter_logcenter_bill_status=='') {
      unset($data['filter_logcenter_bill_status']);  
      unset($filter['lb.status']);
    }

    $sort = I('get.sort');
    $order = I('get.order');
    if($order) {
      $order = $order=='DESC'?'ASC':'DESC';
    }

    $sort_data = array(
      'sort' => $sort?$sort:'logcenter_bill_id',
      'order' => $order?$order:'DESC',
    );

    $data['order'] = $sort_data['order'];
    $data['sort'] = $sort_data['sort'];

    $url .= '&order=' . $sort_data['order'];

    $data['sort_logcenter_bill'] = $this->url->link('sale/logcenter_bill', 'token=' . $this->session->data['token'] . '&sort=lb.logcenter_bill_id' . $url, 'SSL');
    $data['sort_logcenter_name'] = $this->url->link('sale/logcenter_bill', 'token=' . $this->session->data['token'] . '&sort=lb.logcenter_name' . $url, 'SSL');
    $data['sort_status'] = $this->url->link('sale/logcenter_bill', 'token=' . $this->session->data['token'] . '&sort=lb.status' . $url, 'SSL');
    $data['sort_year_month'] = $this->url->link('sale/logcenter_bill', 'token=' . $this->session->data['token'] . '&sort=lb.year_month' . $url, 'SSL');
    $data['sort_date_added'] = $this->url->link('sale/logcenter_bill', 'token=' . $this->session->data['token'] . '&sort=lb.date_added' . $url, 'SSL');
    $data['sort_date_modified'] = $this->url->link('sale/logcenter_bill', 'token=' . $this->session->data['token'] . '&sort=lb.date_modified' . $url, 'SSL');

    
    if($this->user->getLp()){
      $filter['lb.logcenter_id'] = $this->user->getLp();
    }
    else{
      
    }

    $logcenter_bill_list =  $this->model_sale_logcenter_bill->getList($page, $filter, $sort_data);
    $bill_total = $this->model_sale_logcenter_bill->getListCount($filter);
    foreach ($logcenter_bill_list as $key => $value) {
      $logcenter_bill_list[$key]['status_name'] = getLogcenterBillStatus()[$value['status']];
    }

    $pagination = new Pagination();
    $pagination->total = $bill_total;
    $pagination->page = $page;
    $pagination->limit = $this->config->get('config_limit_admin');
    $pagination->url = $this->url->link('sale/logcenter_bill', 'token=' . $this->session->data['token'] . '&page={page}', 'SSL');

    $data['pagination'] = $pagination->render();

    $data['breadcrumbs'] = array();

    $data['breadcrumbs'][] = array(
      'text' => $this->language->get('text_home'),
      'href' => $this->url->link('common/dashboard', 'token=' . $this->session->data['token'], 'SSL')
    );

    $data['breadcrumbs'][] = array(
      'text' => '物流营销中心对账单',
      'href' => $this->url->link('sale/logcenter_bill', 'token=' . $this->session->data['token'] , 'SSL')
    );

    if (isset($this->session->data['error'])) {
      $data['error_warning'] = $this->session->data['error'];

      unset($this->session->data['error']);
    } elseif (isset($this->error['warning'])) {
      $data['error_warning'] = $this->error['warning'];
    } else {
      $data['error_warning'] = '';
    }

    if (isset($this->session->data['success'])) {
      $data['success'] = $this->session->data['success'];

      unset($this->session->data['success']);
    } else {
      $data['success'] = '';
    }

    $data['logcenter_bill_statuses'] = getLogcenterBillStatus();

    $data['token'] = $this->session->data['token'];
    
    $data['logcenter_bills'] = $logcenter_bill_list;

    $data['header'] = $this->load->controller('common/header');
    $data['column_left'] = $this->load->controller('common/column_left');
    $data['footer'] = $this->load->controller('common/footer');

    $this->response->setOutput($this->load->view('sale/lgi_logcenter_bill_list.tpl', $data));
  }

  // public function setLogcenterBillDiff() {
  //   if ($this->request->server['REQUEST_METHOD'] == 'POST') {
  //     $this->load->model('sale/logcenter_bill');
  //     $data = json_decode(file_get_contents('php://input'), true);
  //     $filter = C('DEFAULT_FILTER');
  //     $data   =   is_array($data) ? array_map_recursive($filter,$data) : $filter($data);
  //     // $id = I('post.po_id');
  //     $id = $data['logcenter_bill_id'];
  //     if(!$id){
  //       $id=0;
  //     }
  //     $logcenter_bill = $this->model_sale_logcenter_bill->getLogcenterBill($id);
  //     //判断logcenter_bill状态，如果是物流中心确认之后的状态则不允许在添加差额
  //     if($logcenter_bill['status'] > 1) {
  //       $this->response->setOutput(json_encode(array('error'=>'不能修改物流中心确认之后的差价')));
  //       return;
  //     }

  //     $difference = $data['difference'];
  //     if($difference) {
  //       $difference = (float)$difference;
  //       $this->model_sale_logcenter_bill->changeDifference($id, $difference);
  //       $this->response->setOutput(json_encode(array('success'=>'修改对账单差价状态成功')));
  //     } else {
  //       $this->response->setOutput(json_encode(array('error'=>'差价不能为空')));
  //     }
  //     return;

  //     $this->response->setOutput(json_encode(array('success'=>'修改采购单状态成功')));
  //     return;
  //   } 
  // }

  public function changeLogcenterBillStatus() {
    if ($this->request->server['REQUEST_METHOD'] == 'POST') {
      $this->load->model('sale/logcenter_bill');
      $data = json_decode(file_get_contents('php://input'), true);
      $filter = C('DEFAULT_FILTER');
      $data   =   is_array($data) ? array_map_recursive($filter,$data) : $filter($data);
      // $id = I('post.po_id');
      $id = $data['logcenter_bill_id'];
      if(!$id){
        $id=0;
      }
      $logcenter_bill = $this->model_sale_logcenter_bill->getLogcenterBill($id);

      switch ($logcenter_bill['status']) {
        case '0':
          $target_status = 1;
          break;
        case '1':
          $target_status = 2;
          break;
        case '2':
          $target_status = 3;
          break;
        case '3':
          $target_status = 4;
          break;
        case '4':
          $target_status = 5;
          break;
        default:
          $target_status = -1;
          break;
      }
      if($target_status == -1) {
        $this->response->setOutput(json_encode(array('error'=>'修改对账单状态失败')));
      } else {
        $this->model_sale_logcenter_bill->changeLogcenterBillStatus($id, $target_status);
        $this->response->setOutput(json_encode(array('success'=>'修改对账单状态成功')));

        //添加生成物流营销对账单操作记录
        $this->load->model('catalog/logcenter');
        $logcenter_info = $this->model_catalog_logcenter->getLogcenterByUserId($this->user->getId());
        $comment = '修改对账单状态为：'.getLogcenterBillStatus()[$target_status];
        $this->model_sale_logcenter_bill->addLogcenterBillHistory($id, $this->user->getId(), $logcenter_info['logcenter_name'], $comment);  

      }
      return;
    } 
  }

}